import time

from game.controllers.controller import GameController
from settings import GAME_SETTINGS
from layers.gameboard import GameBoard
import util.events.event as ev


class Game():
    def __init__(self, evManager):
        self.eventManager = evManager
        self.eventManager.RegisterListener(self)
        self.running = False
        self.gameBoard = GameBoard()
        self.turnCounter = TurnCounter()
        self.eventQueue = EventQueue()
        
    def doTurn(self):
        #get actions from current creatures
        #perform any queued actions
        #go to the next turn
        turn = self.turnCounter.currentTurn()
        print turn
        for entity in self.gameBoard.entities:
            pass
            #entity.getAction()
        for event in self.eventQueue.readQueue(turn):
            pass
            #event.doEvent()
        self.turnCounter.nextTurn()
        self.gameBoard.drawBoard()
        
    def addEntity(self, x, y, entity):
        try:
            self.gameBoard.placeTile(x, y, entity)
        except:
            raise
    
    def run(self):
        self.running = True
        #while self.running:
        #    self.doTurn()
            
    def pause(self):
        self.running = False
        
    def togglePause(self, event):
        if self.running: self.running=False
        else: self.running = True
            
    def Notify(self, event):
        if isinstance(event, ev.PauseEvent):
            self.togglePause()
        elif isinstance(event, ev.ToggleVisionEvent):
            if self.gameBoard.showVisionLayer:
                    self.gameBoard.showVisionLayer = False
                    self.gameBoard.drawBoard()
            else:
                self.gameBoard.showVisionLayer = True
                self.gameBoard.drawBoard()
        

class TurnCounter(object):
    def __init__(self, turn=GAME_SETTINGS.STARTING_TURN):
        self.turn=turn
    
    def nextTurn(self):
        self.turn += GAME_SETTINGS.TICKS_PER_TURN
        return self.turn
        
    def currentTurn(self):
        return self.turn
    
class EventQueue(object):
    def __init__(self):
        self.queue = {}
        
    def addToQueue(self, event, turn):
        if self.queue.has_key(turn):
            self.queue[turn].append(event)
        else:
            self.queue[turn]=[event]
    
    def readQueue(self, turn):
        try:
            x = self.queue.pop(turn)
            return x
        except KeyError:
            return []
        